//
//  BSRecommendViewController.m
//  BaiSi
//
//  Created by Sycamore on 16/5/9.
//  Copyright © 2016年 Sycamore. All rights reserved.
//

#import "BSRecommendViewController.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import <AFNetworking/AFNetworking.h>
#import "BSCategoryItem.h"
#import "BSUsersItem.h"
#import "BSCategotyCell.h"
#import "BSTagCell.h"

@interface BSRecommendViewController () <UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *categoryTableView;

@property (weak, nonatomic) IBOutlet UITableView *usersTableView;
@property (nonatomic,weak) AFHTTPSessionManager *manager;

@property (nonatomic,strong) NSArray *categoryList;
@property (nonatomic,strong) NSMutableArray *usersList;
@property (nonatomic,strong) BSCategoryItem *selectedItem;

@end
static NSString * const categoryID = @"category";
static NSString * const usersID = @"users";

@implementation BSRecommendViewController

- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"推荐标签";
    
    //请求网络数据
    [self loadData];
    
    //当一个页面有多个scrollView的时候，导航条只会对其中一个scrollview添加额外的滚动距离（我们可以先清空，然后每个再自己设置额外的滚动距离）
    self.automaticallyAdjustsScrollViewInsets = NO;
    _categoryTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    _usersTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    
    
    //注册cell
    [_categoryTableView registerNib:[UINib nibWithNibName:@"BSCategotyCell" bundle:nil] forCellReuseIdentifier:categoryID];
    [_usersTableView registerNib:[UINib nibWithNibName:@"BSTagCell" bundle:nil] forCellReuseIdentifier:usersID];
    
    //添加上下拉刷新
    [self addHeaderRefreshView];
    [self addFooterRefreshView];
    
}

//添加下拉刷新
- (void)addHeaderRefreshView
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadUserData)];
    header.automaticallyChangeAlpha = YES;
    _usersTableView.mj_header = header;
}

//添加上拉刷新
- (void)addFooterRefreshView
{
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUserData)];
    footer.automaticallyHidden = YES;
    _usersTableView.mj_footer = footer;
}

#pragma mark  请求网络数据
//请求分组数据
- (void)loadData
{
    NSDictionary *parameters = @{
                                 @"a" : @"category",
                                 @"c" : @"subscribe"
                                 };
    [self.manager GET:BSBaseURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {

//      [responseObject writeToFile:@"/Users/Sycamore/Desktop/BaiSi.plist" atomically:YES];
        NSArray *listArray = [responseObject objectForKey:@"list"];
        //替换模型里的默写属性名称，以和字典的key对应
        [BSCategoryItem mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{
                     @"ID" : @"id"
                     };
        }];
        //获得左侧tableView的模型数组
        _categoryList = [BSCategoryItem mj_objectArrayWithKeyValuesArray:listArray];
        
        
        [_categoryTableView reloadData];
        
        //刷新数据后，默认选中第一个cell
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        //直接调用此方法会有bug,第一个选中的cell会永远处于选中状态
//        BSCategotyCell *cell = [_categoryTableView cellForRowAtIndexPath:indexPath];
//        [cell setSelected:YES animated:YES];
        
        //此方法不会调用cell选中的代理方法
        [_categoryTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        
        //调用代理方法，选中第一行，代理去加载user数据
        [self tableView:_categoryTableView didSelectRowAtIndexPath:indexPath];
    } failure:nil];
}

//请求用户数据
- (void)loadUserData
{
    NSDictionary *parameters = @{
                                 @"a" : @"list",
                                 @"c" : @"subscribe",
                                 @"category_id" : _selectedItem.ID
                                 };
    [self.manager GET:BSBaseURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
//        [responseObject writeToFile:@"/Users/Sycamore/Desktop/BaiSi.plist" atomically:YES];
        NSArray *listArray = [responseObject objectForKey:@"list"];
        //获得左侧tableView的模型数组
        _usersList = [BSUsersItem mj_objectArrayWithKeyValuesArray:listArray];
        
        //记得结束刷新
        [_usersTableView.mj_header endRefreshing];
        
        //为分组模型里添加属性
        _selectedItem.next_page = [responseObject[@"next_page"] integerValue];
        _selectedItem.total_page = [responseObject[@"total_page"] integerValue];
        
        //记录当前选中组的用户
        _selectedItem.users = _usersList;
        
        [_usersTableView reloadData];
        
        //判断是否需要显示底部刷新view
        _usersTableView.mj_footer.hidden = _selectedItem.next_page > _selectedItem.total_page;
        
        
    } failure:nil];

}

//加载更多数据
- (void)loadMoreUserData
{
    NSDictionary *parameters = @{
                                 @"a" : @"list",
                                 @"c" : @"subscribe",
                                 @"category_id" : _selectedItem.ID,
                                 @"page" : [NSString stringWithFormat:@"%ld",_selectedItem.next_page]
                                 };
    [self.manager GET:BSBaseURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
//        [responseObject writeToFile:@"/Users/Sycamore/Desktop/BaiSi.plist" atomically:YES];
        
        //记得结束刷新
        [_usersTableView.mj_header endRefreshing];
        
        NSArray *listArray = [responseObject objectForKey:@"list"];
        //获得左侧tableView的模型数组
        [_usersList addObjectsFromArray:[BSUsersItem mj_objectArrayWithKeyValuesArray:listArray]];
        
        //为分组模型里添加属性
        _selectedItem.next_page = [responseObject[@"next_page"] integerValue];
        
        //记录当前选中组的用户
        _selectedItem.users = _usersList;
        
        [_usersTableView reloadData];
        
        //判断是否需要显示底部刷新view
        _usersTableView.mj_footer.hidden = _selectedItem.next_page > _selectedItem.total_page;
        
        
    } failure:nil];

}

#pragma mark  UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _categoryTableView) {
        return _categoryList.count;
    }
    return _selectedItem.users.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if(tableView == _categoryTableView){
        cell = [tableView dequeueReusableCellWithIdentifier:categoryID ];
        BSCategotyCell *categoryCell = (BSCategotyCell *)cell;
        categoryCell.item = _categoryList[indexPath.row];
    }
    else{
       cell = [tableView dequeueReusableCellWithIdentifier:usersID ];
        BSTagCell *tagCell = (BSTagCell *)cell;
        tagCell.usersItem = _selectedItem.users[indexPath.row];
        
    }

    //这里只要返回cell就行了，没必要搞清楚到底是哪种cell,运行的时候会自己区分的
        return cell;
}

#pragma mark  UITableViewDelegate
//选中cell的时候会调用此方法（在cell的setSelected方法后调用此方法）
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果选中的是左边的分组
    if (tableView == _categoryTableView) {
        
        //记录选中的item
        _selectedItem = _categoryList[indexPath.row];
        
        //判断是否真的需要加载数据（如果之前已经加载过，就不需要加载了
        if (_selectedItem.users.count > 0) {
            //直接刷新表格，不需要加载数据
            [_usersTableView reloadData];
            
            //判断是否需要显示底部刷新view
            _usersTableView.mj_footer.hidden = _selectedItem.next_page > _selectedItem.total_page;
            return;
        }
        //如果没保存过数据需要加载网络数据
        [self loadUserData];
//        [_usersTableView.mj_header beginRefreshing];  //这个方法就会调用loadUserData方法，只不过还加有下拉刷新的功能
        
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _categoryTableView) {
        return 44;
    }
    return 60;
}


@end
